<script setup>
import {defineProps} from 'vue'

const props = defineProps({
  text: String, // 原始文本
  keywords: Array, // 关键字列表
  color: String, // 关键字的颜色
  styleObject: Object,
  keyWordStyleObject: Object
})

const  objectToCssString = (styles) => {
  const cssProperties = Object.keys(styles)
  const cssString = cssProperties.map(property => {
    const value = styles[property]
    return `${property}: ${value}`
  }).join('; ')
  return cssString
}

const highlightKeywords = () => {
  let highlightedText = props.text
  props.keywords?.forEach(keyword => {
    const regex = new RegExp(keyword, 'g')
    highlightedText = highlightedText.replace(regex, `<span style="color: ${props.color}; ${objectToCssString(props.keyWordStyleObject)}">${keyword}</span>`)
  })
  return `<span style="${objectToCssString(props.styleObject)}">${highlightedText}</span>`
}

</script>

<template>
  <p v-html="highlightKeywords()"></p>
</template>

<style scoped lang="scss">

</style>